import { EditOutlined, DeleteOutlined, PlusOutlined } from '@ant-design/icons'
import { Button, Modal, message } from 'antd'
import c from 'classnames'
import BeautyMenu from '@/desktop/components/BeautyMenu'
import services from '@/services'
import type { AccountGroup } from '@/services/features/accounts'
import './Groups.module.less'

import EditGroup from './EditGroup'

export default function Groups(props: {
  groups: AccountGroup[]
  selectedId: number | null
  select: (group: AccountGroup) => void
  refresh: () => void
}) {
  const { groups, selectedId, select, refresh } = props

  const [editing, setEditing] = useState<AccountGroup | true | null>(null)
  const finishEdit = useCallback(() => {
    setEditing(null)
    refresh()
  }, [refresh])

  const removeGroup = useCallback(
    (id: number) => {
      void Modal.confirm({
        title: '确定要移除此分组吗？',
        async onOk() {
          const res = await services.features.accounts.removeGroup(id)
          if (res === true) {
            void message.success('分组已移除')
            refresh()
          } else {
            void message.warning(`分组移除失败：${res}`)
          }
        },
      })
    },
    [refresh],
  )

  return <>
    <div styleName="groups-wrap">
      <header>
        <label>分组列表</label>
        <Button
          size="small"
          icon={<PlusOutlined />}
          type="primary"
          onClick={() => setEditing(true)}
        >
          新建分组
        </Button>
      </header>
      <div styleName="groups">
        {groups.map(item => <GroupItem
          key={item.id}
          item={item}
          isSelected={selectedId === item.id}
          onSelect={select}
          onEdit={setEditing}
          onRemove={removeGroup}
        />)}
      </div>
    </div>

    <EditGroup
      visible={editing !== null}
      group={editing === true ? undefined : editing ?? undefined}
      onFinish={finishEdit}
    />
  </>
}

function GroupItem(props: {
  item: AccountGroup
  isSelected: boolean
  onSelect: (item: AccountGroup) => void
  onEdit: (item: AccountGroup) => void
  onRemove: (id: number) => void
}) {
  const { item, isSelected, onSelect, onEdit, onRemove } = props
  const accountNum = item.accountIds.length

  const styleName = c('group', isSelected ? 'selected' : '')
  const select = useCallback(() => onSelect(item), [item, onSelect])
  const menuItems = useMemo(
    () => [
      {
        icon: <EditOutlined />,
        title: '编辑',
        onClick: () => onEdit(item),
      },
      {
        icon: <DeleteOutlined />,
        title: '移除',
        onClick: () => onRemove(item.id),
      },
    ],
    [item, onEdit, onRemove],
  )

  return <div styleName={styleName} onClick={select} key={item.id}>
    <span styleName="name">{item.name}</span>
    <span styleName="count">
      <span styleName={accountNum ? '' : 'empty'}>{accountNum}</span>
    </span>
    <BeautyMenu items={menuItems} />
  </div>
}
